/**
* Copyright @ 2023 iAuto (Shanghai) Co., Ltd.
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are NOT permitted except as agreed by
* iAuto (Shanghai) Co., Ltd.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
//
import defaultProject from './default-project';
import Storage from 'scratch-storage';

class MyStorage extends Storage {
  constructor() {
    super();
    this.cacheDefaultProject();
  }
  // 添加 Scratch 网络存储
  addOfficialScratchWebStores() {
    this.addWebStore(
      [this.AssetType.Project],
      this.getProjectGetConfig.bind(this),
      this.getProjectCreateConfig.bind(this),
      this.getProjectUpdateConfig.bind(this),
    );
    this.addWebStore(
      [this.AssetType.ImageVector, this.AssetType.ImageBitmap, this.AssetType.Sound],
      this.getAssetGetConfig.bind(this),
      // 我们将 create 和 update 的配置都设置为相同的方法，因为存储假设如果有 assetId，那么应该进行更新，但是
      // 资源存储使用 assetId 作为创建 URI 的一部分。
      this.getAssetCreateConfig.bind(this),
      this.getAssetCreateConfig.bind(this),
    );
    this.addWebStore(
      [this.AssetType.Sound],
      (asset) => `static/extension-assets/scratch3_music/${asset.assetId}.${asset.dataFormat}`,
    );
  }
  // 设置项目主机
  setProjectHost(projectHost) {
    this.projectHost = projectHost;
  }
  // 获取项目获取配置
  getProjectGetConfig(projectAsset) {
    return `${this.projectHost}/${projectAsset.assetId}`;
  }
  // 获取项目创建配置
  getProjectCreateConfig() {
    return {
      url: `${this.projectHost}/`,
      withCredentials: true,
    };
  }
  // 获取项目更新配置
  getProjectUpdateConfig(projectAsset) {
    return {
      url: `${this.projectHost}/${projectAsset.assetId}`,
      withCredentials: true,
    };
  }
  // 设置资源主机
  setAssetHost(assetHost) {
    this.assetHost = assetHost;
  }
  // 获取资源获取配置
  getAssetGetConfig(asset) {
    return `${this.assetHost}/internalapi/asset/${asset.assetId}.${asset.dataFormat}/get/`;
  }
  // 获取资源创建配置
  getAssetCreateConfig(asset) {
    return {
      // 没有更新资源的概念，但是存储假设如果有 assetId，那么应该进行更新，而资源存储使用
      // assetId 作为创建 URI 的一部分。因此，强制使用 POST 方法。
      // 然后当存储找到此配置用于“更新”时，仍然会进行 POST。
      method: 'post',
      url: `${this.assetHost}/${asset.assetId}.${asset.dataFormat}`,
      withCredentials: true,
    };
  }
  // 设置翻译器函数
  setTranslatorFunction(translator) {
    this.translator = translator;
    this.cacheDefaultProject();
  }
  // 缓存默认项目
  cacheDefaultProject() {
    const defaultProjectAssets = defaultProject(this.translator);
    defaultProjectAssets.forEach((asset) =>
      this.builtinHelper._store(
        this.AssetType[asset.assetType],
        this.DataFormat[asset.dataFormat],
        asset.data,
        asset.id,
      ),
    );
  }
}

const storage = new MyStorage();

export default storage;
